from flask import Flask, render_template,request
import json

app = Flask(__name__)

@app.route('/')
def hello_wold():
    return 'Hello World!!'

@app.route('/hello')
def hello():
    return '''
        <html>
            <body>
                <h1 style="color:#e00;">
                    Hello World!!
                </h1>
            </body>
        </html>
    '''

@app.route('/hello2')
def hello_2():
    data = "hello data"
    return render_template("hello.html",data=data)

@app.route('/user/<username>', methods=['GET','POST'])
def get_user(username):
    return 'hello %s' %username

@app.route('/data',methods=['GET','POST'])
def test_data():
    '''
    print(request.args)
    print(request.args.get('a'),request.args.get('b'))
    print(request.headers)
    print(request.headers.get('User-Agent'))
    print(request.data)
    import json
    print(json.loads(request.data))
    print(request.cookies)
    print(request.cookies.get('token'))

    '''

    print(request.form)
    print(request.form.get('2q'),request.form.get('password'))
    return 'success'

@app.route("/use_template")
def use_template():
    datas = [(1,"name1"),(2,"name2"),(3,"name3")]
    title = "学生信息"
    return render_template('use_template.html',datas=datas,title=title)


def read_pvuv():
    '''
    read pv uv
    :return:
    '''
    data = []
    with open("./data/pvuv.txt") as fin:
        is_fist_line = True
        for line in fin:
            if is_fist_line:
                is_fist_line = False
                continue
            line = line[:-1]
            pdate, pv, uv = line.split("\t")
            data.append((pdate, pv, uv))
    return data

@app.route('/pvuv')
def pvuv():
    data = read_pvuv()
    return render_template('pvuv.html',data=data)

@app.route('/getjson')
def getjson():
    data = read_pvuv()
    return json.dumps(data)

@app.route('/show_add_user')
def show_add_user():
    return render_template('show_add_user.html')

from db import insert_or_update_data,query_data
@app.route('/do_add_user',methods=['POST'])
def do_add_user():
    print(request.form)
    name = request.form.get("name")
    age = request.form.get("age")
    sex = request.form.get("sex")
    email = request.form.get("email")
    sql = f"""
        insert into user (name,sex,age,email)
        values ('{name}','{sex}','{age}','{email}')
    """
    insert_or_update_data(sql)
    return "success!"

@app.route('/show_users')
def show_users():
    sql = "select id,name from user"
    datas = query_data(sql)
    return render_template('show_users.html',datas=datas)

@app.route('/show_user/<user_id>')
def show_user(user_id):
    sql = "select * from user where id="+user_id
    datas = query_data(sql)
    user = datas[0]
    return render_template('show_user.html', user = user)



if __name__ == '__main__':
    app.run()